package com.avocado.base.service.impl;



import java.util.ArrayList;
import java.util.List;

import com.avocado.base.dto.organization.OrganizationAddDto;
import com.avocado.base.dto.organization.OrganizationEditDto;
import com.avocado.base.vo.OrganizationAntdTree;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.avocado.base.entity.Organization;
import com.avocado.base.repository.OrganizationRepository;
import com.avocado.base.service.OrganizationService;


@Service
public class OrganizationServiceImpl implements OrganizationService {
	

	private final OrganizationRepository organizationRepository;

	public OrganizationServiceImpl(OrganizationRepository organizationRepository) {
		this.organizationRepository = organizationRepository;
	}

	@Override
	 public Long add(OrganizationAddDto t) {

		Organization organization=new Organization();

		BeanUtils.copyProperties(t,organization);

		organizationRepository.saveAndFlush(organization);
			
		return organization.getId();
	}
	    
	    
	    @Override
	    public void update(OrganizationEditDto t) {

	      	Organization old= organizationRepository.getOne(t.getId());

			BeanUtils.copyProperties(t,old);

			organizationRepository.saveAndFlush(old);

		}
		
	    @Override
	    @Transactional(propagation = Propagation.REQUIRES_NEW,rollbackFor=Exception.class)
	    public  Boolean deleteById(Long id) {

			Organization old= organizationRepository.getOne(id);

			long totalCount= organizationRepository.getCountByParentId(id);

			if (totalCount>0){

				return Boolean.FALSE;
			}

			organizationRepository.delete(old);

			return Boolean.TRUE;

		}
	    @Override
	    public List<OrganizationAntdTree> getTree(){

			List<Organization> organizationList= organizationRepository.findAll();

			return this.convertList(organizationList,0L);
		}

		private List<OrganizationAntdTree> convertList(List<Organization> organizationList,long parentId){

			List<OrganizationAntdTree> treeList=new ArrayList<>();

			for(Organization organization:organizationList){

				OrganizationAntdTree organizationAntdTree=OrganizationAntdTree.builder().id(organization.getId())
						.key("organization_key_".concat(String.valueOf(organization.getId())))
						.title(organization.getName())
						.parentId(organization.getParentId())
						.code(organization.getCode())
						.originTitle(organization.getName())
						.sortOrder(organization.getSortOrder())
						.build();

                if(organization.getParentId()==parentId){

					organizationAntdTree.setChildren(this.convertList(organizationList,organization.getId()));

					treeList.add(organizationAntdTree);
				}

			}

            return treeList;
		}





}
